var express = require('express');
var router = express.Router();
let con = require("../model/db.js");
const { name } = require('ejs');
/* GET home page. */
router.get('/show', function (req, res, next) {
  // con.query("SELECT * FROM student", (err, result) => {
  //   if (err) throw err;
  //   res.render('index', { student: result[0] });
  // })
  res.render("index");
});
router.get('/list', function (req, res, next) {
  con.query("SELECT * FROM student", (err, result) => {
    if (err) throw err;
    res.json(result);
  })
});
router.post('/add', function (req, res, next) {
  const { body } = req;
  con.query("INSERT INTO `student` (name,class,sid) VALUES (?,?,?)", [body.name, body.class, body.sid], (err, result) => {
    if (err) throw err;
    if (result.affectedRows == 1) {
      return res.status(200).send({ code: 200, msg: '添加成功' });
    } else {
      return res.status(500).send({ code: 500, msg: '添加失败' });
    }
  })
});
router.delete('/delete/:id', function (req, res, next) {
  const { id } = req.params;
  con.query('DELETE FROM `student` WHERE id = ?', id, (err, result) => {
    if (err) throw err;
    if (result.affectedRows == 1) {
      return res.status(200).json({ code: 200, msg: '删除成功' });
    } else {
      return res.status(500).json({ code: 500, msg: '删除失败' });
    }
  })
})
router.get('/select/:id', function (req, res, next) {
  const { id } = req.params;
  con.query("SELECT * FROM `student`WHERE id=?", id, (err, result) => {
    if (err) throw err;
    res.json({
      msg: "查询成功",
      code: 200,
      data: result[0]
    })
  })
});
router.put('/update/:id', function (req, res, next) {
  const { id } = req.params;
  const { body } = req;
  con.query("UPDATE `student` SET name=?,sid=?,class=? WHERE id=?", [body.name, body.sid, body.class, id], (err, result) => {
    if (err) throw err;
    if (result.affectedRows == 1) {
      return res.status(200).json({ code: 200, msg: '编辑成功' });
    } else {
      return res.status(500).json({ code: 500, msg: '编辑失败' });
    }
  })
})
module.exports = router;
